<?php

namespace app\admin\controller;
use app\common\controller\Backend;
use app\admin\model\Admin;
use app\common\model\Wechats;
use app\common\model\Materials;
/**
 * 公众号管理
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Wechat extends Backend
{
	/**
     * @var \app\common\model\Wechats
     */
    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\common\model\Wechats');
    }
    public function index(){
    	if ($this->request->isAjax()) {
    		$map=[];
    		if($this->auth->id != $this->admin_id){
    			$wechatIds = (new Admin)->getWechatIds($this->auth->id);
    			$map['id'] = array('in',$wechatIds);
    		}
    		list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    		$list = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
			$result = array("total" => $list->total(), "rows" => $list->items());
			return json($result);
    	}
    	return $this->view->fetch();
    }
    public function add(){
    	if($this->request->isPost()){
    		$data = $this->request->post('row/a');
    		if(empty($data['token'])){
    			$data['token'] = strtoupper(md5(rand(1000000,9999999).time()));
    		}else{
    			$data['token'] = strtoupper($data['token']);
    		}
            $data['token'] = substr($data['token'], 0,16);
    		$result = $this->model->insert($data,true,true);
    		if($result){
                //复制公众号
                $wechatId = $this->request->post('wechatId');
                if(intval($wechatId) > 0){
                    $ws = $this->request->post('w/a');
                    if(is_array($ws)){
                        foreach($ws as $w){
                            $type = 'cp';
                            if($w == 'follow'){
                                $w = 'follow';
                                $type = 'message';
                            }
                            \fast\Async::hook($w,['wechat_id'=>$wechatId,'wechatId'=>$result,'type'=>$type]);
                        }
                    }
                    
                }
    			$this->success('数据保存成功');
    		}
            
            
    		$this->error('数据保存失败');
    	}
    	$this->assign('token',strtoupper(md5(time())));
    	return $this->view->fetch();
    }
    public function edit($ids=null){
    	$map=[];
		if($this->auth->id != $this->admin_id){
			$wechatIds = (new Admin)->getWechatIds($this->auth->id);
			if(!in_array($ids, $wechatIds)){
				$this->error("对不起，权限不足");
			}
		}
    	$row = $this->model->get($ids);
    	if(empty($row)){
    		$this->error(__('数据不存在.'));
    	}
    	if($this->request->isPost()){
    		$data = $this->request->post('row/a');
    		if(empty($data['token'])){
    			$data['token'] = strtoupper(md5(rand(1000000,9999999).time()));
    		}else{
    			$data['token'] = strtoupper($data['token']);
    		}
            $data['token'] = substr($data['token'], 0,16);
    		$data['update_at'] = time();
    		$result = $row->data($data)->save();
    		if($result){
                //复制公众号
                $wechatId = $this->request->post('wechatId');
                if(intval($wechatId) > 0){
                    $ws = $this->request->post('w/a');
                    if(is_array($ws)){
                        foreach($ws as $w){
                            $type = 'cp';
                            if($w == 'follow'){
                                $w = 'follow';
                                $type = 'message';
                            }
                            \fast\Async::hook($w,['wechat_id'=>$wechatId,'wechatId'=>$ids,'type'=>$type]);
                        }
                    }
                }
    			$this->success('数据保存成功');
    		}
    		$this->error('数据保存失败');
    	}
    	$this->assign('row',$row);
        $this->assign('ip',$this->request->Ip());
        $this->assign('api_url',$this->request->domain()."/api/cgi/handle/token/".$row['token']);
    	return $this->view->fetch();
    }
    public function del($ids=null){
    	if($this->auth->id != $this->admin_id){
			$wechatIds = (new Admin)->getWechatIds($this->auth->id);
			if(!in_array($ids, $wechatIds)){
				$this->error("对不起，权限不足");
			}
		}
    	return parent::del($ids);
    }
    /**
     *微信菜单
     */
   function getInstanceWchatMenu()
    {
        $wx_menu = db('wx_menu');
        $foot_menu = $wx_menu->where(['wechat_id'=>$this->wechat_id,'pid'=>0])->order('sort asc')->select();
        if (! empty($foot_menu)) {
            foreach ($foot_menu as $k => $v) {
                $foot_menu[$k]['child'] = '';
                $second_menu = $wx_menu->where(['wechat_id'=>$this->wechat_id,'pid'=>$v['menu_id']])->order('sort asc')->select();
                if (! empty($second_menu)) {
                    $foot_menu[$k]['child'] = $second_menu;
                    $foot_menu[$k]['child_count'] = count($second_menu);
                } else {
                    $foot_menu[$k]['child_count'] = 0;
                }
            }
        }
        return $foot_menu;
    }

    // 微信菜单
    public function menu(){
        $menu_list = $this->getInstanceWchatMenu();
        define('MAX_MENU_LENGTH',3);
        define('MAX_SUB_MENU_LENGTH',5);
        $menu_keys= array_keys($menu_list);
        $default_menu_info = array(); // 默认显示菜单
        $menu_list_count = count($menu_list);
        $class_index = count($menu_list);
        if ($class_index > 0) {
            if ($class_index == MAX_MENU_LENGTH) {
                $class_index = MAX_MENU_LENGTH - 1;
            }
        }
        if ($menu_list_count > 0) {
            $default_menu_info = $menu_list[$menu_list_count - 1];
        } else {
            $default_menu_info["menu_name"] = "";
            $default_menu_info["menu_id"] = 0;
            $default_menu_info["child_count"] = 0;
            $default_menu_info["media_id"] = 0;
            $default_menu_info["menu_event_url"] = "";
            $default_menu_info["menu_event_type"] = 1;
        }
        $media_detail = array();
        if ($default_menu_info["media_id"]) {
            // 查询图文消息
            $media_detail = $this->gwmd($default_menu_info["media_id"]);
            $media_detail["item_list_count"] = count($media_detail["item_list"]);
        } else {
            $media_detail["create_time"] = "";
            $media_detail["title"] = "";
            $media_detail["item_list_count"] = 0;
        }
        $default_menu_info["media_list"] = $media_detail;
        //echo "<pre>";
        //print_r($menu_list);exit;
        $this->assign("wx_name",$this->currentWechatName);
        $this->assign("pagesize",2);
        $this->assign("menu_list", $menu_list);
        $this->assign("MAX_MENU_LENGTH", MAX_MENU_LENGTH); // 一级菜单数量
        $this->assign("MAX_SUB_MENU_LENGTH", MAX_SUB_MENU_LENGTH); // 二级菜单数量
        $this->assign("menu_list_count", $menu_list_count);
        //dump($default_menu_info);
        $this->assign("default_menu_info", $default_menu_info);
        $this->assign("class_index", ($class_index >= 3 ? 3 : $class_index+1));
        return $this->view->fetch();
    }
    public function gwmd($media_id)
    {
        $wx_media = db('wx_media');
        $weixin_media_info = $wx_media->find($media_id);
        $weixin_media_info['create_time'] = toDate($weixin_media_info['create_time'],'Y-m-d H:i:s');
        if (! empty($weixin_media_info)) {
            $item_list = db('wx_media_item')->where(['media_id' => $media_id])->select();
            $weixin_media_info['item_list'] = $item_list;
        }
        return $weixin_media_info;
    }
    public function addweixinmenu($id=null,$pid=null){
        $menu = input('menu');
        if($id>0){
            $row = db('wx_menu')->where(['wechat_id'=>$this->wechat_id,'menu_id'=>$id])->find();
            if(empty($row)){
                 return ['code'=>0,'msg'=>'菜单信息不存在.','data'=>''];
            }
            $row['options'] = json_decode($row['options'],true);
            // 是否图文
            if(isset($row['options']['type']) && $row['options']['type'] == 'mpnews'){
                $rows = Materials::get(intval($row['options']['material_id']));
                if(!empty($rows)){
                    $items = (new Materials)->getMaterialItems($rows->id);
                }
                $this->view->engine->layout(false);
                $this->assign('row',$rows);
                $this->assign('items',$items);
                $row['html'] = $this->view->fetch('material/getItem');
            }
            return ['code'=>1,'msg'=>'','data'=>$row];
        }else{
           if(intval($pid) <= 0 && db('wx_menu')->where(['pid'=>0,'wechat_id'=>$this->wechat_id])->count() >= 3){
              return ['code'=>0,'msg'=>'一级菜单最多添加3个','data'=>''];
           }
           if(intval($pid) > 0 && db('wx_menu')->where(['pid'=>$pid,'wechat_id'=>$this->wechat_id])->count() >= 5){
              return ['code'=>0,'msg'=>'二级级菜单最多添加5个','data'=>''];
           }
           $data['menu_name'] = "新增菜单";
           $data['wechat_id'] = $this->wechat_id;
           $data['pid'] = intval($pid);
           $data['menu_event_type'] = 2;
           $data['menu_event_url'] = '';
           $data['create_date'] = time();
           if($data['menu_id'] = db('wx_menu')->insert($data,false,true)){
             return ['code'=>1,'msg'=>'添加成功','data'=>$data];
           }
        }
        return ['code'=>0,'msg'=>'新增菜单失败.','data'=>''];
    }
    public function updateweixinmenuname()
    {
        $wx_menu = db('wx_menu');
        $data = $this->request->post();
        if(empty($data['menu_name'])){
            $this->error('请输入菜单名称');
        }
        unset($data['row']);
        $opt = $this->request->post('row/a');
        // 跳转链接 View类型
        if($data['menu_event_type'] == 1){
            if(empty($data['menu_event_url'])){
                $this->error('请输入跳转链接');
            }
        }
        if($data['menu_event_type'] == 3){
            if(empty($opt['appid'])){
                $this->error('请输入小程序APPID');
            }
            $data['options'] = json_encode($opt,JSON_UNESCAPED_UNICODE);
        }
        // 点击事件 click
        if($data['menu_event_type'] == 2){
            switch ($opt['type']) {
                case 'image':
                    if(empty($opt['media_id'])){
                        $this->error("请上传推送图片");
                    }
                    break;
                case 'mpnews':
                    if(empty($opt['material_id'])){
                        $this->error("请选择推送图文信息");
                    }
                    break;
                default:
                    if(empty($opt['content'])){
                        $this->error("请输入回复文字内容");
                    }
                    break;
            }
            $data['options'] = json_encode($opt,JSON_UNESCAPED_UNICODE);
        }
        if(intval($data['menu_id']) > 0 ){
            $retval = $wx_menu->where(['wechat_id'=>$this->wechat_id,'menu_id'=>$data['menu_id']])->update($data);
            //$this->scMenu();
            $this->success('菜单保存成功',"/reload");
        }
        return ['code'=>0,'msg'=>'菜单保存失败'];
    }
    /*自定义生成菜单*/
    public function scmenu(){       
        $res = (new \app\common\logic\Wechat)->createMenu($this->wechat_id);
        if($res === true){
            $this->success(__('菜单已经成功生成！'));
        }else{
            $this->error(__('生成失败：'.(isset($res['errmsg']) ? $res['errmsg'] : '未知错误')));
        }
    }
    // 删除菜单
    public function deleteWeixinMenu()
    {
        $menu_id = input('menu_id');
        if (! empty($menu_id)) {
            $res = db('wx_menu')->where("menu_id=$menu_id or pid=$menu_id")->where(['wechat_id'=>$this->wechat_id])->delete();
            return ['code'=>1,'msg'=>'数据删除成功',"url"=>"/reload"];
        }
        return ['code'=>0,'msg'=>'数据删除失败','url'=>''];
    }
    // 同步数据
    public function synch($action="",$ids=null){

        if($this->request->isPost()){
            $wechatIds = $this->request->post('wechat/a');
            if(!empty($wechatIds)){
                foreach($wechatIds as $wechatId){
                    if($action == 'keywork'){
                        \fast\Async::hook('keywork',['wechat_id'=>$this->wechat_id,'ids'=>$ids,'wechatId'=>$wechatId]);
                    }
                    if($action == 'menu'){
                        \fast\Async::hook('menu',['wechat_id'=>$this->wechat_id,'wechatId'=>$wechatId]);
                    }
                    
                }
            }
            $this->success('同步数据成功');
        }
        return $this->view->fetch();
    }
}